<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Log;
use App\Models\User;

class SyncOfficialAccount extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'csw:SyncOfficialAccount';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info("csw:SyncOfficialAccount start!");

        $app = app('wechat.official_account');
        $isEnd = false;
        $nextOpenId = null;
        while(!$isEnd) {
            $list  = $app->user->list($nextOpenId);
            if(isset($list['data']) && isset($list['data']['openid']) && $list['data']['openid']) {
                foreach($list['data']['openid'] as $openid) {
                    $this->info($openid);
                    $userObj = User::firstOrCreate(['openid' => $openid]);
                    if(!$userObj->nickname) {
                        $userRemote = $app->user->get($openid);
                        if($userRemote) {
                            $userObj->subscribe = $userRemote['subscribe'];
                            $userObj->nickname = $userRemote['nickname'];
                            $userObj->language = $userRemote['language'];
                            $userObj->sex = $userRemote['sex'];
                            $userObj->city = $userRemote['city'];
                            $userObj->country = $userRemote['country'];
                            $userObj->headimgurl = $userRemote['headimgurl'];
                            $userObj->subscribe_time = $userRemote['subscribe_time'];
                            $userObj->remark = $userRemote['remark'];
                            $userObj->tagid_list = json_encode($userRemote['tagid_list']);
                            $userObj->groupid = $userRemote['groupid'];
                            $userObj->subscribe_scene = $userRemote['subscribe_scene'];
                            $userObj->qr_scene = $userRemote['qr_scene'];
                            $userObj->qr_scene_str = $userRemote['qr_scene_str'];
                            $userObj->save();
                        }
                    }
                }
            }
            if(isset($list['next_openid']) && $list['next_openid']) {
                $nextOpenId = $list['next_openid'];

            } else {
                $isEnd = true;
            }
            break;
        }

        $this->info("csw:SyncOfficialAccount end!");
    }
}
